from PyQt6.QtWidgets import (
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QLineEdit,
    QPushButton,
    QTextEdit,
    QLabel,
)

from .interfaces import IClientView


class ClientGUI(QWidget, IClientView):
    """TCP客户端图形界面"""

    def __init__(self):
        super().__init__()
        self.setWindowTitle("TCP Client")
        self.resize(600, 400)
        self._init_ui()

    def _init_ui(self):
        # 连接控制区域
        self.host_input = QLineEdit("127.0.0.1")
        self.port_input = QLineEdit("8080")
        self.connect_btn = QPushButton("连接")
        self.disconnect_btn = QPushButton("断开")
        self.disconnect_btn.setEnabled(False)

        control_layout = QHBoxLayout()
        control_layout.addWidget(QLabel("服务器:"))
        control_layout.addWidget(self.host_input)
        control_layout.addWidget(QLabel("端口:"))
        control_layout.addWidget(self.port_input)
        control_layout.addWidget(self.connect_btn)
        control_layout.addWidget(self.disconnect_btn)

        # 数据发送区域
        self.send_input = QLineEdit()
        self.send_btn = QPushButton("发送")

        send_layout = QHBoxLayout()
        send_layout.addWidget(self.send_input)
        send_layout.addWidget(self.send_btn)

        # 消息显示区域
        self.log_area = QTextEdit()
        self.log_area.setReadOnly(True)

        # 主布局
        main_layout = QVBoxLayout()
        main_layout.addLayout(control_layout)
        main_layout.addWidget(self.log_area)
        main_layout.addLayout(send_layout)
        self.setLayout(main_layout)

    # 实现接口方法
    def update_connection_status(self, connected: bool):
        self.connect_btn.setEnabled(not connected)
        self.disconnect_btn.setEnabled(connected)
        self.host_input.setEnabled(not connected)
        self.port_input.setEnabled(not connected)

    def display_received_data(self, data: str):
        print(f"[接收] {data}")
        self.log_area.append(f"[接收] {data}")

    def show_error_message(self, message: str):
        self.log_area.append(f"[错误] {message}")

    def get_connection_params(self) -> tuple:
        return (self.host_input.text().strip(), int(self.port_input.text().strip()))

    def get_send_data(self) -> str:
        return self.send_input.text()
